source('codes/00_import_libraries.R')


#-----------------------------------------------------------------------------#
# data ------------------------------------------------------------------------
#-----------------------------------------------------------------------------#

crisis = readRDS('input/uncertainty_and_crisis_indexes.rds')

dt = readRDS('input/combined_data.rds')[['base']] %>% 
  select(ym, War, contains('mkt')) %>% 
  mutate(across(contains('mkt'), ~ .x*12)) %>% 
  inner_join(crisis, by = 'ym') |> 
  drop_na(NVIX2)



#-----------------------------------------------------------------------------#
# function --------------------------------------------------------------------
#-----------------------------------------------------------------------------#

fn_res = function(x_list, beg_yr, h) {
  
  mod_list = lapply(x_list, function(x) {
    fn_fit_ols(
      df   = dt %>% filter(year(ym) >= beg_yr), 
      xvar = x, 
      yvar = paste0('mkt', h)
    )
  })

  mod_robust = lapply(mod_list, function(mod) {
    coeftest(mod, vcov. = NeweyWest(mod, lag = h, prewhite = F))
  })
  
  r2 = lapply(mod_list, function(mod) glance(mod)$adj.r.squared * 100) %>%
    unlist()
  
  out = huxreg(
    mod_robust
    , coefs        = x_list %>% unlist() %>% unique()
    , error_format = "({statistic})"
    , stars        = c(`***` = 0.01, `**` = 0.05, `*` = 0.1)
    , statistics   = c(0)
    , borders      = 0
    , outer_borders= 0
    , note         = NULL
  )
  
  rbind(out[-1, ], c('$R^2$', r2)) 
}



#-----------------------------------------------------------------------------#
# Panel A: NVIX and GPR -------------------------------------------------------
#-----------------------------------------------------------------------------#

panel_list = c('1900-2016', '1950-2016', '2000-2016')
x_list = list('War', 'NVIX2', 'GPR', c('War', 'NVIX2'), c('NVIX2', 'GPR'))


out = lapply(c(1900, 1950, 2000), function(y) {
  fn_res(x_list = x_list, beg_yr = y, h = 1)
})


output = lapply(seq_along(out), function(i) {
  out[[i]] %>% 
    insert_row(panel_list[i], fill = '') %>% 
    merge_across(1, everywhere) %>% 
    set_align(1, everywhere, 'center') %>% 
    set_number_format(1, everywhere, 0) %>% 
    set_number_format(-1, -1, 2) %>% 
    set_tb_borders(1, everywhere, 0.8) %>% 
    set_bottom_border(final(1), everywhere, 0.8)
}) %>% 
  do.call(what = rbind) %>% 
  as_hux() %>% 
  set_all_padding(0) %>% 
  set_escape_contents(F)


output[c(4,12,20),1] = 'NVIX\\textsuperscript{2}'
quick_xlsx(output, file = glue('output/tables/Table_6A.xlsx'))

